//
//  MaintenanceAddRelatedOneViewController.m
//  OA
//
//  Created by yy on 17/9/13.
//  Copyright © 2017年 yy. All rights reserved.
//
#import "RegionChooseViewController.h"
#import "BumenViewController.h"
#import "MaintenanceAddRelatedOneViewController.h"
#import "BasisAddCollectionViewCell.h"
#import "QBImagePickerController.h"
#import "csCell.h"
#import "csAddCell.h"

//
//#import <AVFoundation/AVFoundation.h>
//#include "amrFileCodec.h"

@interface MaintenanceAddRelatedOneViewController ()<TimeChouseDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UINavigationControllerDelegate,UIImagePickerControllerDelegate,QBImagePickerControllerDelegate,UIScrollViewDelegate>//RegionChooseDelegate
@property (weak, nonatomic) IBOutlet UIView *backView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *backViewBottom;
//完成时间
@property (weak, nonatomic) IBOutlet UIView *endTimeView;
@property (weak, nonatomic) IBOutlet UILabel *endTimeL;
//处理人
@property (weak, nonatomic) IBOutlet UIView *dealView;
@property (weak, nonatomic) IBOutlet UILabel *dealPersonL;
@property (weak, nonatomic) IBOutlet UIButton *dealBtn;
@property (weak, nonatomic) IBOutlet UIImageView *dealImg;
//
@property (weak, nonatomic) IBOutlet UILabel *cityL;
@property (copy, nonatomic) NSString *cityId;

@property (weak, nonatomic) IBOutlet UIImageView *cityImg;
@property (weak, nonatomic) IBOutlet UIButton *cityBtn;

@property (weak, nonatomic) IBOutlet UITextView *contentTextView;
@property (weak, nonatomic) IBOutlet UILabel *receivingTimeL;//接收时间
@property (weak, nonatomic) IBOutlet UIImageView *emergencyImg;//
@property (weak, nonatomic) IBOutlet UIButton *oneEmergencyBtn;//302 301 300
@property (weak, nonatomic) IBOutlet UIButton *twoEmergencyBtn;
@property (weak, nonatomic) IBOutlet UILabel *emergencyL;
@property (weak, nonatomic) IBOutlet UIButton *thrEmergencyBtn;
@property (weak, nonatomic) IBOutlet UILabel *lineTimeL;
@property (weak, nonatomic) IBOutlet UITextField *noteTextF;
//
@property (nonatomic,strong)BasisChooseTimeView *viewOfDate;

@property (nonatomic,strong)NSMutableDictionary *dicOfdataSource;
@property (nonatomic,strong)NSMutableDictionary *dicOfdealPerson;


@property (weak, nonatomic) IBOutlet UIButton *soundBtn;
@property (weak, nonatomic) IBOutlet UIView *imgBackView;
@property (weak, nonatomic) IBOutlet UICollectionView *imgCollectionView;//图片选择

@property (weak, nonatomic) IBOutlet UICollectionView *personChooseCollectionView;
@property (nonatomic,strong) NSMutableArray *personChooseArr;//抄送人

@property (nonatomic, strong) UIAlertController *alertController;//表单
@property (nonatomic, strong) QBImagePickerController *imagePickerController; //相册
@property (nonatomic,strong)  UIImagePickerController *photoPickerController; //相机
@property (nonatomic,strong) NSMutableArray *allDataimgMutableArray;//全部
@property (nonatomic,strong) NSMutableArray *imageMutableArray;//相册
@property (nonatomic,strong) NSMutableArray *selectedarr;//选中状态
@property (nonatomic,strong) NSMutableArray *photoMutableArray;//照片
@property (nonatomic,assign) int imgphotoArrNum;//照片的数量
@property (nonatomic,assign) int numLine;//cell最大数
@property (nonatomic,assign) BOOL isQBImagePicker;//照相还是图片
@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) UIImageView *imageView;
//
//@property (strong, nonatomic) AVAudioRecorder *audioReorder;
//@property (strong, nonatomic) AVAudioPlayer *audioPlayer;
@property (strong, nonatomic) AVAudioRecorder *recorder;
@property (strong, nonatomic) AVAudioPlayer *audioPlayer;
@property (nonatomic,strong) NSMutableArray *arrOfFileurl;
@property (nonatomic,strong) NSMutableArray *arrOfFileDate;

@end

@implementation MaintenanceAddRelatedOneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeUserInterface];
}
- (void)initializeUserInterface{
    self.title = @"新增运维";
    _cityImg.hidden = NO;
    _dealView.hidden = YES;
    _endTimeView.hidden = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notice:) name:@"regionChooseInfo"object:nil];
    _noteTextF.enabled = YES;
    _contentTextView.editable = YES;
    _dicOfdataSource = [NSMutableDictionary dictionary];
    [_dicOfdataSource setObject:@"4" forKey:@"urgency"];
    _dealBtn.userInteractionEnabled = NO;
    [self addSaveBtn];
    [self initOfDataSouce];
    _arrOfFileurl = [NSMutableArray array];
    _arrOfFileDate = [NSMutableArray array];
    [self initSounds];
}
#pragma mark ——————initOfDataSouce
- (void)initOfDataSouce{
    _cityL.text = [ShareUserInfo sharedUserInfo].userModel.myUnitName;
    if ([_cityL.text isEqualToString:@"重庆亚亮科技有限公司"]) {
        _cityBtn.userInteractionEnabled = YES;
        _cityL.text = @"";
        _cityImg.hidden = NO;
       
    }else{
        _cityBtn.userInteractionEnabled = NO;
        _cityImg.hidden = YES;
    }
    [self collectionViewInit];
}
#pragma mark —————— 语音相关init

- (void)initSounds{
    NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc]init];
    //设置录音格式  AVFormatIDKey==kAudioFormatLinearPCM
    [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
    //设置录音采样率(Hz) 如：AVSampleRateKey==8000/44100/96000（影响音频的质量）
    [recordSetting setValue:[NSNumber numberWithFloat:44100] forKey:AVSampleRateKey];
    //录音通道数  1 或 2
    [recordSetting setValue:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey];
    //线性采样位数  8、16、24、32
    [recordSetting setValue:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
    //录音的质量
    [recordSetting setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
    
    NSString* path = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp/aaa"];
    NSURL* url = [NSURL fileURLWithPath:path];
    
    _recorder = [[AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:nil];
    //准备录音
    [_recorder prepareToRecord];

}

//- (void)initWithSound{
//    _arrOfFileurl = [NSMutableArray array];
//    _arrOfFileDate = [NSMutableArray array];
//    //音频设备
//    AVAudioSession *session=[AVAudioSession sharedInstance];
//    NSError *sessionError;
//    
//    //控制当前录音播放的时候其他的音频是关闭状态。否则无法播放
//    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
//    
//    if (sessionError) {
//        NSLog(@"error:%@",sessionError.localizedDescription);
//    }
//    else
//    {
//        [session setActive:YES error:nil];
//    }
//    
//    [self initOfSoundName];
//
//}
//- (void)initOfSoundName{
//    //录音文件保存路径
//    //获取一个沙盒的Document的路径。。lastObject指是进去我们的Document文件夹。。NSUserDomainMask指当前的APP的沙盒中去查找。
//    
//    NSURL *url=[[[NSFileManager defaultManager]URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
//    //给我们录音文件起个名字
//   NSString *name = [NSString stringWithFormat:@"voice_corder%lu.caf",(unsigned long)_arrOfFileurl.count];
//    NSURL *voiceUrl=[url URLByAppendingPathComponent:name];
//    //配置audioRecorder
//    NSDictionary *recordSet=[NSDictionary dictionaryWithObjectsAndKeys:
//                             [NSNumber numberWithInt:AVAudioQualityLow],AVEncoderAudioQualityKey,//录音质量
//                             [NSNumber numberWithInt:16],AVEncoderBitRateKey,//编码率
//                             [NSNumber numberWithInt:2],AVNumberOfChannelsKey,//
//                             [NSNumber numberWithFloat:44100.0],AVSampleRateKey,
//                             nil];
//    
//    NSError *error;
//    self.audioReorder=[[AVAudioRecorder alloc] initWithURL:voiceUrl settings:recordSet error:&error];
//    if (error) {
//        NSLog(@" audiorecorder error:%@",error.localizedDescription);
//    }
//    else
//    {
//        if ([self.audioReorder prepareToRecord]) {
//            NSLog(@"recorder is ready!");
//        }
//    }
//}
#pragma mark ——————collectionViewInit
- (void)collectionViewInit{
    //图片
    _imgCollectionView.delegate = self;
    _imgCollectionView.dataSource = self;
    
  
    _allDataimgMutableArray = [NSMutableArray array];
    
    _selectedarr = [NSMutableArray array];
    _imageMutableArray = [NSMutableArray array];
    _photoMutableArray = [NSMutableArray array];
    _numLine = 6;
    _imgphotoArrNum = 0;
    
    [self initOfPhotoPicker];
    
    //抄送人
    _personChooseCollectionView.delegate = self;
    _personChooseCollectionView.dataSource = self;
    _personChooseArr = [NSMutableArray array];
    
    
    
}
#pragma mark —————— regionChoose

- (void)notice:(NSNotification *)regionNotification{
    NSDictionary *dic = regionNotification.userInfo;
    _cityL.text = [NSString stringWithFormat:@"%@",[dic objectForKey:@"name"]];
    _cityId = [NSString stringWithFormat:@"%@",[dic objectForKey:@"id"]];
}
- (void)initializeUserInterfaceWithData{
    
    MaintenanceModel *model = [MaintenanceModel objectWithKeyValues:_dicOfdataSource];
    
    _cityL.text = model.regionName;
    _contentTextView.text = model.content;
    _receivingTimeL.text = [model.receivedate substringWithRange:NSMakeRange(0, 10)];
    _lineTimeL.text = [model.lookdate substringWithRange:NSMakeRange(0, 10)];
    _endTimeL.text = [model.finishdate substringWithRange:NSMakeRange(0, 10)];
    _noteTextF.text = model.note;
    if (_typeOfNum == 0 && _dicOfdealPerson.allKeys.count ==0) {
        _dealPersonL.hidden = YES;
        _dealImg.hidden = NO;
    }else{
        _dealPersonL.hidden = NO;
        _dealImg.hidden = YES;
        _dealPersonL.text = model.lookers;
    }
    
    [self urgencyType:model.urgency];
    
    
}
- (void)urgencyType:(NSString *)type{
    _oneEmergencyBtn.hidden = YES;
    _twoEmergencyBtn.hidden = YES;
    _thrEmergencyBtn.hidden = YES;
    
    
    switch ([type intValue]) {
        case 0:
            _emergencyL.text = @"一般";
            _emergencyL.textColor = BlueColor;
            break;
        case 1:
            _emergencyL.text = @"中等";
            _emergencyL.textColor = OrageStatusColor;
            break;
        case 2:
            _emergencyL.text = @"紧急";
            _emergencyL.textColor = RedColor;
            
            break;
        default:
            break;
    }
    _emergencyImg.hidden = YES;
    
}
#pragma mark —————— UIBarButtonItem
- (void)addSaveBtn{
    UIBarButtonItem *saveBtn = [[UIBarButtonItem alloc]initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(saveBtnActionYw:)];
    self.navigationItem.rightBarButtonItem = saveBtn;
}
#pragma mark —————— 保存
- (void)saveBtnActionYw:(UIBarButtonItem *)sender{
    NSLog(@"保存");
    NSMutableDictionary *parms = [NSMutableDictionary dictionary];
    NSString *url = @"";
    switch (_typeOfNum) {
        case -1:
            self.title = @"新增运维";
            if (_cityId.length == 0  || _cityL.text.length == 0) {
                [MBProgressHUD showError:@"请选择区域"];
                return;
            }else{
                [parms setObject:_cityL.text forKey:@"regionName"];//区域名称
                [parms setObject:_cityId forKey:@"regionId"];//区域id
            }
            [parms setObject:_contentTextView.text forKey:@"content"];//内容
            _receivingTimeL.text = [ToolOfBasic nowTime];
            [parms setObject:_receivingTimeL.text forKey:@"receivedate"];//接受时间
            [parms setObject:_lineTimeL.text forKey:@"lookdate"];//处理期限
            [parms setObject:_dicOfdataSource[@"urgency"] forKey:@"urgency"];//紧急程度：1,2,3
            [parms setObject:_noteTextF.text forKey:@"note"];
            
            NSMutableArray *imgNameArr = [NSMutableArray array];
            for (int i = 0; i <_allDataimgMutableArray.count; i ++) {//图片名字
                [imgNameArr addObject:[NSString stringWithFormat:@"%d.png",i]];
            }
            NSMutableArray *voiceNameArr = [NSMutableArray array];
            for (int i = 0; i <_arrOfFileurl.count; i ++) {//声音名字
//                [voiceNameArr addObject:[NSString stringWithFormat:@"%d.caf",i]];
                [voiceNameArr addObject:[NSString stringWithFormat:@"%d.amr",i]];
            }
            [parms setObject:[voiceNameArr componentsJoinedByString:@";"] forKey:@"voice"];
            [parms setObject:[imgNameArr componentsJoinedByString:@";"] forKey:@"Img"];
            
            //经纬度
            [parms setObject:@"" forKey:@"longitude"];
            [parms setObject:@"" forKey:@"latitude"];
            
            NSMutableArray *arrayWhom = [NSMutableArray array];
            NSMutableArray *arrayWhomId = [NSMutableArray array];
            for (int i = 0; i <_personChooseArr.count; i++) {
                [arrayWhom addObject:_personChooseArr[i][@"name"]];
                [arrayWhomId addObject:_personChooseArr[i][@"id"]];
            }
            //抄送人
            [parms setObject:[arrayWhom componentsJoinedByString:@";"] forKey:@"toWhom"];
            [parms setObject:[arrayWhomId componentsJoinedByString:@";"] forKey:@"toWhomId"];
            
 
            url = oa_saveOperations;
            break;
  
    }
    NSLog(@"parms==%@",parms);
   //_arrOfFileDate  _arrOfFileurl
//    [[ToolOfNetWork sharedTools]YrequestURL:url withParams:parms fileData:_allDataimgMutableArray fileVoiceData:_arrOfFileurl finished:^(id responsObject, NSError *error) {
   
    [[ToolOfNetWork sharedTools]YrequestURL:url withParams:parms fileData:_allDataimgMutableArray fileVoiceData:_arrOfFileurl finished:^(id responsObject, NSError *error) {
        if (_Success) {
            if (_typeOfNum == -1) {
                _ref();
            }else{
                if(_ref !=nil){
                    _ref();
                }
            }
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            Y_MBP_ErrMessage
        }
    }];
//    [[ToolOfNetWork sharedTools]YrequestURL:url withParams:parms finished:^(id responsObject, NSError *error) {
//        if (_Success) {
//            if (_typeOfNum == -1) {
//                _ref();
//            }else{
//                if(_ref !=nil){
//                    _ref();
//                }
//            }
//            [self.navigationController popViewControllerAnimated:YES];
//        }else{
//            Y_MBP_Error
//        }
//    }];
}

#pragma mark —————— block 返回刷新
- (void)refreshAction:(RefreshMaintenaceVc)refresh{
    
    if (_typeOfNum == -1) {
        _ref = refresh;
    }else{
        if (_ref!=nil) {
            _ref = refresh;
        }
        
    }
   
}


- (void)showEmergencyView{
    int typeNum = [[NSString stringWithFormat:@"%@",_dicOfdataSource[@"urgency"]] intValue];
    switch (typeNum) {
        case 2:
            _oneEmergencyBtn.hidden = NO;
            _twoEmergencyBtn.hidden = YES;
            _thrEmergencyBtn.hidden = YES;
            break;
        case 1:
            _oneEmergencyBtn.hidden = YES;
            _twoEmergencyBtn.hidden = NO;
            _thrEmergencyBtn.hidden = YES;
            break;
        case 0:
            _oneEmergencyBtn.hidden = YES;
            _twoEmergencyBtn.hidden = YES;
            _thrEmergencyBtn.hidden = NO;
            break;
            
        default://4
            _oneEmergencyBtn.hidden = NO;
            _twoEmergencyBtn.hidden = NO;
            _thrEmergencyBtn.hidden = NO;
            break;
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark ——————语音 soundBtn
- (IBAction)soundBtnAction:(UIButton *)sender {
     NSLog(@"声音");
    
    sender.selected = !sender.selected;
    
    if (sender.selected == NO) {
        [sender setTitle:@"再开始" forState:UIControlStateNormal];
        NSLog(@"stop");
        [self stopRecordTofile];
        [_recorder stop];
    }else{
        [sender setTitle:@"结束" forState:UIControlStateNormal];
        NSLog(@"begin");
        [self soundwirteTofile];
        [_recorder record];
    }
//    [MBProgressHUD showSuccess:@"正在录音"];
//    NSLog(@"点击btnOfBeginSoundAction");
//    
//    if (self.audioReorder.recording) {//停止
//        [self.audioReorder stop];
//        NSLog(@"recording is stop");
//         [sender setTitle:@"录音" forState:UIControlStateNormal];
//        [_arrOfFileurl addObject:self.audioReorder.url];//存路径
//        [self initOfSoundName];//下一个路径名字
//        [self changeSound:_arrOfFileurl.lastObject];
//    }
//    else
//    {// 录音
//        [self.audioReorder record];
//        NSLog(@"begin record!");
//        [sender setTitle:@"停止" forState:UIControlStateNormal];
// 
//    }
    

}


- (void)soundwirteTofile{
    
    NSString* path = [NSHomeDirectory() stringByAppendingPathComponent:@"download/aaa"];
    
    [[EMCDDeviceManager sharedInstance] asyncStartRecordingWithFileName:path completion:^(NSError *error)
     {
         if (error) {
             NSLog(@"%@",NSEaseLocalizedString(@"message.startRecordFail", @"failure to start recording"));
         }else{
             NSLog(@"%@",[NSURL fileURLWithPath:path]);
         }
     }];
}
- (void)stopRecordTofile{
    [[EMCDDeviceManager sharedInstance] asyncStopRecordingWithCompletion:^(NSString *recordPath, NSInteger aDuration, NSError *error) {
        if (!error) {
            //获取到的录音地址，自己存起来。也可以写入FileManage中，这里我写入了沙盒中。
            dispatch_async(dispatch_get_main_queue(), ^{
                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                [user setObject:recordPath forKey:@"music"];
                [user setObject:[NSNumber numberWithInteger:aDuration] forKey:@"musicTime"];
                [_arrOfFileurl addObject:recordPath];
            });
        }
    }];
    
}
//播放与停止
#pragma mark ——————sound Opening
- (void)btnOfOpeningAction:(UIButton *)sender{
//    NSLog(@"点击btnOfOpeningAction");
//    if (self.audioPlayer.playing) {
//        [self.audioPlayer stop];
//    }
//    else
//    {
//        NSError *error=nil;
//        self.audioPlayer=[[AVAudioPlayer alloc] initWithContentsOfURL:self.audioReorder.url error:&error];
//        [self.audioPlayer play];
//        NSLog(@"begin play!");
//    }
}
#pragma mark —————— 声音格式转换
- (void)changeSound:(NSURL *)url{
    
//    
//    NSData *da = EncodeWAVEToAMR([NSData dataWithContentsOfURL:url], 1, 16);
//    [_arrOfFileDate addObject: da];
//    
//    NSLog(@"%@",da);
//    __weak __typeof(self) weakSelf = self;
    
//    [[RecordManager shareManager] writeAuToAmrFile:url callback:^(BOOL success, NSData *amrData) {
//        if (success) {
//            [weakSelf play:amrData];
//            
//        }
//    }];
}

- (void)play:(NSData*)data{
//    NSData *data = [NSData dataWithContentsOfFile:path];
//    [[RecordManager shareManager] playAmrData:data];
//    NSData *da = DecodeAMRToWAVE(data);
//     [_arrOfFileDate addObject: da];
}
#pragma mark ——————

//区域选择
- (IBAction)cityBtnAciton:(UIButton *)sender {//310
    if (_typeOfNum == -1) {
//        if (_cityL.text.length>0) {
//            return;
//        }
        RegionChooseViewController *regionChooseVc = Y_storyBoard_id(@"RegionChooseViewController");
        regionChooseVc.regionName = _cityL.text;
        [self.navigationController pushViewController:regionChooseVc animated:YES];
    }
}

//紧急程度
- (IBAction)emergencyBtnAction:(UIButton *)sender {//urgency012
    NSInteger tag = sender.tag-TAG_BTN_C;
    NSLog(@"%ld",(long)tag);
    
    int i = [[NSString stringWithFormat:@"%@",_dicOfdataSource[@"urgency"]] intValue];
    if (i == 4) {
        [_dicOfdataSource setObject:[NSString stringWithFormat:@"%ld",(long)tag] forKey:@"urgency"];
        [self showEmergencyView];
    }else{
        [_dicOfdataSource setObject:@"4" forKey:@"urgency"];//清空状态
        [self showEmergencyView];
    }
    
}
//接收时间
- (IBAction)receivingTimeBtnAction:(UIButton *)sender {//312
    [self.view endEditing:YES];
    
    if (_typeOfNum == -1) {
        [self getTiemViewWithTag:sender.tag];
    }
}
//处理期限
- (IBAction)lineTimeBtnAction:(UIButton *)sender {//313
    [self.view endEditing:YES];
    
    NSLog(@"处理期限");
    if (_typeOfNum == -1 ||_typeOfNum == 0) {//分配+新增
        [self getTiemViewWithTag:sender.tag];
    }
    
}

//完成时间
- (IBAction)endTimeBtn:(UIButton *)sender {//315
    [self.view endEditing:YES];
    
    NSLog(@"完成时间");
    [self getTiemViewWithTag:sender.tag];
}

- (void)getTiemViewWithTag:(NSInteger)tag{
    [self.view addSubview:self.viewOfDate];
    _viewOfDate.tag = tag;
}
#pragma mark ——————
//处理人
- (IBAction)dealPersonBtnAction:(UIButton *)sender {//314
//    NSLog(@"处理人");
//    //    _dealPersonL.text = @""
//    BumenChoiceViewController *bumenVc = VCInSB(@"BumenChoiceViewController", @"BumenViewController");
//    bumenVc.type = @"1";
//    bumenVc.vc = self;
//    if (_dicOfdealPerson.allKeys.count == 0) {
//        bumenVc.csshArr = @[];
//    } else {
//        bumenVc.csshArr = [NSArray arrayWithObject:_dicOfdealPerson];
//        
//    }
//    bumenVc.back = ^() {
//        if ([ShareUserInfo sharedUserInfo].csArr.count>0) {
//            _dicOfdealPerson = [[ShareUserInfo sharedUserInfo].csArr objectAtIndex:0];
//            NSString *strOfname =  _dicOfdealPerson[@"name"];
//            if (strOfname.length>2) {
//                strOfname =  [strOfname substringWithRange:NSMakeRange(strOfname.length-2, 2)];
//            }
//            [self initializeUserInterfaceWithData];
//            _dealPersonL.text = strOfname;
//            
//        }
//    };
//    [self.navigationController pushViewController:bumenVc animated:YES];
    
}

//抄送人审核人的协议

#pragma mark —————— timeChoose
-(BasisChooseTimeView *)viewOfDate{
    if (!_viewOfDate) {
        _viewOfDate = [[[NSBundle mainBundle]loadNibNamed:@"BasisChooseTimeView" owner:self options:nil]objectAtIndex:0];
        _viewOfDate.frame = CGRectMake(30, 30, Y_mainW-60, 280);
        _viewOfDate.center = self.view.center;
        _viewOfDate.layer.cornerRadius = 20;
        _viewOfDate.layer.borderWidth = 0.2;
        _viewOfDate.delegateOfTime = self;
        _viewOfDate.isPrecision = NO;
    }
    return _viewOfDate;
}
- (NSString *)dateOfDidSelect:(NSString *)str{
    NSInteger tag = _viewOfDate.tag;
    switch (tag-TAG_BTN_C) {
        case  12://接收时间
            _receivingTimeL.text  = str;
            break;
        case  13://处理期限
            _lineTimeL.text = str;
            break;
        case  15://完成时间
            _endTimeL.text = str;
            break;
            
        default:
            break;
    }
    [_viewOfDate removeFromSuperview];
    
    return str;
}
- (void)removeBasisChooseTimeView{
    [_viewOfDate removeFromSuperview];
}
#pragma mark --will
- (void)viewDidAppear:(BOOL)animated
{
    [self reloadDataAndCollectionView];
    
}
#pragma mark --刷新

- (void)reloadDataAndCollectionView{
    
    if (!_isQBImagePicker) {
        [self.allDataimgMutableArray removeAllObjects];
        [self.allDataimgMutableArray addObjectsFromArray:_imageMutableArray];//图片
        [self.allDataimgMutableArray addObjectsFromArray:_photoMutableArray];//照片
    }else{
        [self.allDataimgMutableArray removeAllObjects];
        [self.allDataimgMutableArray addObjectsFromArray:_photoMutableArray];//照片
        [self.allDataimgMutableArray addObjectsFromArray:_imageMutableArray];//图片
    }
//    if (self.allDataimgMutableArray.count<=2) {
//        NSLayoutConstraint *h = _heightIOfCollectionView;
//        h.constant = 130;
//        _heightIOfCollectionView = h;
//        
//        
//    }else{
//        NSLayoutConstraint *h = _heightIOfCollectionView;
//        h.constant = 260;
//        _heightIOfCollectionView = h;
//    }
//    
    [self.imgCollectionView  reloadData];
    
}
#pragma mark --initQBImagePickerController

- (QBImagePickerController *)imagePickerController{
    if (!_imagePickerController) {
        _imagePickerController = [[QBImagePickerController alloc]init];
        _imagePickerController.prompt = @"图片选择";
        _imagePickerController.allowsMultipleSelection = YES;//多选yse
        _imagePickerController.showsNumberOfSelectedAssets = YES;
        _imagePickerController.delegate = self;
        _imagePickerController.mediaType = QBImagePickerMediaTypeImage;
        _imagePickerController.maximumNumberOfSelection = _numLine-_imgphotoArrNum;//最大上限
        
        _imagePickerController.assetCollectionSubtypes = @[
                                                           @(PHAssetCollectionSubtypeSmartAlbumUserLibrary), //相机胶卷
                                                           @(PHAssetCollectionSubtypeAlbumMyPhotoStream), //我的照片流
                                                           @(PHAssetCollectionSubtypeSmartAlbumPanoramas), //全景
                                                           @(PHAssetCollectionSubtypeSmartAlbumBursts) //连拍模式拍摄的照片
                                                           ];
        
    }
    
    [_imagePickerController.selectedAssets removeAllObjects];
    _imagePickerController.selectedAssets = [NSMutableOrderedSet orderedSetWithArray:_selectedarr];
    
    return _imagePickerController;
}

#pragma mark --initOfPhotoPicker
-(void)initOfPhotoPicker{
    _photoPickerController = [[UIImagePickerController alloc] init];
    _photoPickerController.delegate = self;
    _isQBImagePicker = YES;

}

#pragma mark --UICollectionViewDataSource
//--CollectionView
//组
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
///元素个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if (collectionView == self.personChooseCollectionView) {
        return self.personChooseArr.count + 1;//抄送人
        
    }else{
        if (self.allDataimgMutableArray.count < _numLine){
            
            return self.allDataimgMutableArray.count+1;//多加一个cell
            
        }else{
            
            return self.allDataimgMutableArray.count;
        }
    }
    
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
 
    if(collectionView == self.personChooseCollectionView) {
        if (indexPath.row < self.personChooseArr.count) {
            csCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"csCell" forIndexPath:indexPath];
            cell.image.backgroundColor = [UIColor getColorWithHexString:@"FEA100"];
            cell.image.layer.cornerRadius = 20;
            cell.image.clipsToBounds = YES;
            
            NSString *nameStr = self.personChooseArr[indexPath.row][@"name"];
            
            if (nameStr.length <3) {
                cell.name.text = nameStr;
            } else {
                cell.name.text = [nameStr substringWithRange:NSMakeRange(nameStr.length - 2, 2)];
            }
            return cell;
        } else {
            csAddCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"csAddCell" forIndexPath:indexPath];
            return cell;
        }
    } else {//图片
    
            BasisAddCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BasisAddCollectionViewCell" forIndexPath:indexPath];
            if (self.allDataimgMutableArray.count < _numLine){
                //
                if (indexPath.item == self.allDataimgMutableArray.count) {
                    cell.imgView.image = [UIImage imageNamed:@"添加Add"];
                    cell.removeBtn.hidden = YES;
                }else{
                    cell.imgView.image = self.allDataimgMutableArray[indexPath.item];
                    cell.removeBtn.hidden = NO;
                    [cell removeOfimg:^{
                        [self deleteCell:indexPath];
                    }];
                }
                
            }else{
                //
                cell.imgView.image = self.allDataimgMutableArray[indexPath.item];
                cell.removeBtn.hidden = NO;
                //删除
                [cell removeOfimg:^{
                    [self deleteCell:indexPath];
                }];
                
            }
            return cell;
    
    }
    
    
    
}

#pragma mark-- cell数据处理
- (void)deleteCell:(NSIndexPath* )indexPath{
    
    
    if (_isQBImagePicker) {
        
        //判断是相册还是照片
        if (indexPath.item < _imageMutableArray.count) {//相册
            
            [_imageMutableArray removeObjectAtIndex:indexPath.item];
            [_selectedarr removeObjectAtIndex:indexPath.item];
            
        }else{//照片
            [_photoMutableArray removeObjectAtIndex:indexPath.item - _imageMutableArray.count];
            _imgphotoArrNum -= 1;
        }
        
    }else{
        
        //判断是相册还是照片
        if (indexPath.item < _photoMutableArray.count) {//照片
            
            [_photoMutableArray removeObjectAtIndex:indexPath.item];
            _imgphotoArrNum -= 1;
            
        }else{//相册
            [_imageMutableArray removeObjectAtIndex:indexPath.item - _photoMutableArray.count];
            [_selectedarr removeObjectAtIndex:indexPath.item - _photoMutableArray.count];
        }
        
    }
    
    [self reloadDataAndCollectionView];
    
}
#pragma mark--UICollectionViewDataSource
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
//    return CGSizeMake(Y_mainW*0.3,Y_mainW*0.3);
//return CGSizeMake(Y_mainW*0.125,Y_mainW*0.125);
    return CGSizeMake(50,50);
    
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 5;
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(5, 5, 5, 5);
    
}
#pragma mark --- UICollectionViewDelegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (collectionView == self.personChooseCollectionView) {
        if (indexPath.row < self.personChooseArr.count) {
            [self.personChooseArr removeObjectAtIndex:indexPath.row];
            [self.personChooseCollectionView reloadData];
        } else {
            BumenChoiceViewController *vc = VCInSB(@"BumenChoiceViewController", @"BumenViewController");
            vc.type = @"1";
            vc.vc = self;
            vc.csshArr = self.personChooseArr;
            vc.back = ^() {
                if ([ShareUserInfo sharedUserInfo].csArr.count > 0) {
                    [self.personChooseArr removeAllObjects];
                    [self.personChooseArr addObjectsFromArray:    [ShareUserInfo sharedUserInfo].csArr];
                    [self.personChooseCollectionView reloadData];
                }
            };
            [self.navigationController pushViewController:vc animated:YES];
            
        }
    }else{
        [collectionView dequeueReusableCellWithReuseIdentifier:@"BasisAddCollectionViewCell" forIndexPath:indexPath];
        if (self.allDataimgMutableArray.count < _numLine) {//添加存在时
            if (indexPath.item == self.allDataimgMutableArray.count) {
                [self photo];
            }else{
                [self img:_allDataimgMutableArray[indexPath.row]];
            }
        }else{
            [self img:_allDataimgMutableArray[indexPath.row]];
        }

    }
 
}


#pragma mark --加载表单
- (void)photo{
    //表单位置
    _alertController = self.alertController;//getter表单
    
    [self presentViewController:self.alertController animated:YES completion:nil];
    
}


//用户选图像
#pragma mark QBImagePickerControllerdelegate---

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets{
    
    if (assets.count > _numLine -_imgphotoArrNum) {
        NSString *str = [NSString stringWithFormat:@"已有照片%ld张,图片不能超过%d张",(long)_imgphotoArrNum,(_numLine - _imgphotoArrNum)];
        [imagePickerController showFailedHUD:str];
        
    }else{
        
        [imagePickerController showWaitingHUDWithMessage:@"选择成功,处理中"];
        
        [self.selectedarr removeAllObjects];
        [self.selectedarr addObjectsFromArray:assets];
        
        [self.imageMutableArray removeAllObjects];//照片
        for (NSInteger i = 0; i < assets.count; i++) {
            [self.imageMutableArray addObject:[NSNull null]];//占位
            
            
        }
        PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
        options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
        dispatch_group_t group = dispatch_group_create();//任务组
        
        for (int i = 0; i < assets.count; i++) {
            dispatch_group_enter(group);//加入任务
            
            [[PHImageManager defaultManager] requestImageForAsset:assets[i] targetSize:[UIScreen mainScreen].bounds.size contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage *result, NSDictionary *info) {
                //设置图片
                self.imageMutableArray[i] = result;
                dispatch_group_leave(group);
            }];
            
        }
        
        
        dispatch_group_notify(group, dispatch_get_main_queue(), ^{
            _isQBImagePicker = YES;
            [imagePickerController dismissHUD];
            [self dismissViewControllerAnimated:YES completion:^{
                _isQBImagePicker = YES;
            }];
            
        });
        
    }
}

- (BOOL)qb_imagePickerController:(QBImagePickerController *)imagePickerController shouldSelectAsset:(PHAsset *)asset{
    return YES;//shouldSelectAsset
}

-(void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController {
    if (imagePickerController.mediaType == QBImagePickerMediaTypeImage) {
        [self dismissViewControllerAnimated:YES completion:^{
        }];
    }
}

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didSelectAsset:(PHAsset *)asset{//选择
    
}


#pragma mark --UIImagePickerControllerDelegate
// 用户选择了拍照
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary <NSString *,id> *)info {
    
    
    
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        
        if ([info[UIImagePickerControllerMediaType] isEqualToString:@"public.image"]) {
            UIImageView *imgView = [[UIImageView alloc]init];
            imgView.contentMode = UIViewContentModeScaleAspectFit;//比例
            imgView.image = info[UIImagePickerControllerOriginalImage];
            UIImage *originalImage = imgView.image;
            if (originalImage) {
                
                [self.photoMutableArray addObject:originalImage];
                _imgphotoArrNum+=1;
                _isQBImagePicker = NO;
            }
        }
    }
    [self dismissViewControllerAnimated:YES completion:nil];
    
}


#pragma mark --alertController getter --
- (UIAlertController *)alertController{
    
    if (!_alertController) {
        _alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请选择图片来源" preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            //            NSLog(@"从相册中选择");
            [self presentViewController:self.imagePickerController animated:YES completion:^{
            }];
            
        }];
        
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSArray * mediatypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
            
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                
                _photoPickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                _photoPickerController.mediaTypes = @[mediatypes[0]];
                _photoPickerController.allowsEditing = YES;
                _photoPickerController.delegate = self;
                
                [self presentViewController:_photoPickerController animated:YES completion:nil];
            } else {
                UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"系统模拟器暂不能提供照相功能" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
                [self presentViewController:alert animated:YES completion:^{
                    
                }];
            } }];
        UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        }];
        
        
        [_alertController addAction:action1];
        [_alertController addAction:action2];
        [_alertController addAction:action3];
        
    }
    return _alertController;
}

#pragma mark --imgBig

- (void)img:(UIImage *)showImg{
    _scrollView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
    _scrollView.maximumZoomScale=5.0;//图片的放大倍数
    _scrollView.minimumZoomScale=1.0;//图片的最小倍率
    _scrollView.contentSize=CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height);
    _scrollView.delegate=self;
    _scrollView.backgroundColor = [[UIColor grayColor]colorWithAlphaComponent:0.3];
    
    _imageView=[[UIImageView alloc]initWithFrame:self.view.bounds];
    _imageView.image = [self scaleImage:showImg toScale:1];
    
    [_scrollView addSubview:_imageView];
    [self.view addSubview:_scrollView];
    
    _imageView.userInteractionEnabled=YES;//注意:imageView默认是不可以交互,在这里设置为可以交互
    self.imgCollectionView.userInteractionEnabled = NO;
    self.backView.userInteractionEnabled = NO;
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapImage:)];
    tap.numberOfTapsRequired=1;//单击
    tap.numberOfTouchesRequired=1;//单点触碰
    [_imageView addGestureRecognizer:tap];
    
    UITapGestureRecognizer *doubleTap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doubleTap:)];
    doubleTap.numberOfTapsRequired=2;//避免单击与双击冲突
    [tap requireGestureRecognizerToFail:doubleTap];
    [_imageView addGestureRecognizer:doubleTap];
    _imageView.contentMode=UIViewContentModeScaleAspectFit;
}

- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}

-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView  //委托方法,必须设置  delegate
{
    return _imageView;//要放大的视图
}

-(void)doubleTap:(id)sender
{
    //    NSLog(@"双击");
    _scrollView.zoomScale=2.0;//双击放大到两倍
}
- (void)tapImage:(id)sender
{
    //    NSLog(@"单击");
    self.backView.userInteractionEnabled = YES;
    self.imgCollectionView.userInteractionEnabled = YES;
    [_scrollView removeFromSuperview];
}



@end
